package com.yuliang.utils.util;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

/**
 * @author admin
 * http工具类
 */
@Slf4j
public class HttpRequestUtils {
    /**
     * 向指定的url发送get请求
     * @param url 请求地址
     * @param param 请求参数
     * */
    public static String sendGet(String url,String param){
        String result = "";
        BufferedReader in=null;
        try{
            String urlNameString = url+"?" +param;
            URL realUrl = new URL(urlNameString);
            //开启与URL建立连接
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("Content-type", "application/json; charset=UTF-8");

            //建立实际的连接
            connection.connect();
            //获取所有的响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            for (String key: map.keySet()){
                log.info(key+ "响应头字段---->{}", map.get(key));
            }
            //定义输入流读取响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while((line = in.readLine()) != null){
                result += line;
            }
            result = new String(result.getBytes(), "UTF-8");
        } catch (Exception e) {
            log.info("发送请求时出现异常");
            e.printStackTrace();
            return null;
        }finally {
            try{
                if (in !=null){
                    in.close();
                }
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }
        log.info("返回的结果", result);
        return result;
    }
    /**
     * 发送请求，已经进行拼接好的url地址发送
     * */
    public static String sendGet(String url){
        String result = "";
        BufferedReader in=null;
        try{
            URL realUrl = new URL(url);
            //开启与URL建立连接
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("Content-type", "application/json; charset=UTF-8");

            //建立实际的连接
            connection.connect();
            //获取所有的响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            for (String key: map.keySet()){
                log.info(key+ "响应头字段---->{}", map.get(key));
            }
            //定义输入流读取响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while((line = in.readLine()) != null){
                result += line;
            }
            result = new String(result.getBytes(), "UTF-8");
        } catch (Exception e) {
            log.info("发送请求时出现异常");
            e.printStackTrace();
        }finally {
            try{
                if (in !=null){
                    in.close();
                }
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }
        log.info("返回的结果", result);
        return result;
    }
    /**
     * 向指定的url请求发送get请求
     * @param url 发送get 请求url,携带token
     * @
     * */
    public static String sendGet(String url, String param, String token) {
        if (StringUtils.isEmpty(token)) {
            return sendGet(url, param);
        }
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            //打开和url之间的连接
            URLConnection connection = realUrl.openConnection();
            //设置通用的请求属性
            connection.setRequestProperty("Content-type", "application/json; charset=UTF-8");
            connection.setRequestProperty("token", token);
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                log.info(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            result = new String(result.getBytes(), "UTF-8");
        } catch (Exception e) {
            log.info("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
    /**
     * 向指定 URL 发送POST方法的请求
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("accept-language", "en-US,en;q=0.5");
            // 发送POST请求,必须设置如下两行，设置是否能够获取到要
            conn.setDoOutput(true);
            //设置
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            log.error("HTTP POST error : {}", e.getMessage());
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                log.error("close IO error : {}", ex.getMessage());
            }
        }
        return result.toString();
    }

    /**
     * 参数放post中的param中（傻逼操作）
     */
    public static String doPost(String url, Map<String, String> header, Map<String, Object> mapParam)  {
        StringBuffer resultContent = new StringBuffer();
        try {
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(url);
            if (mapParam != null && mapParam.size() > 0) {
                stringBuffer.append("?");
                for (Map.Entry<String, Object> entry : mapParam.entrySet()) {
                    String key = entry.getKey();
                    Object value = entry.getValue();
                    stringBuffer.append(key + "=" + value.toString());
                    stringBuffer.append("&");
                }
                stringBuffer.replace(stringBuffer.length() - 1, stringBuffer.length(), "");
            }
            OkHttpClient client = new OkHttpClient();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "");
            Request request = new Request.Builder()
                    .url(stringBuffer.toString())
                    .method("POST", body)
                    .addHeader("referrer", header.get("referrer"))
                    .build();

            Response response = client.newCall(request).execute();
            return response.body().string();
        }catch (Exception e){
            e.printStackTrace();
        }
        return resultContent.toString();
    }

    /**
     * post请求
     * */
    public static String doPost(String url, Map<String, String> header, String body) {
        StringBuffer stringBuffer = new StringBuffer();
        BufferedReader in;
        PrintWriter out;
        try {
            // 设置 url
            URL realUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection)realUrl.openConnection();
            // 设置 header
            for (String key : header.keySet()) {
                connection.setRequestProperty(key, header.get(key));
            }
            // 设置请求 body
            connection.setDoOutput(true);
            connection.setDoInput(true);

            //设置连接超时和读取超时时间
            connection.setConnectTimeout(20000);
            connection.setReadTimeout(20000);
            try {
                out = new PrintWriter(connection.getOutputStream());
                // 保存body
                out.print(body);
                // 发送body
                out.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                // 获取响应body
                in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                while ((line = in.readLine()) != null) {
                    stringBuffer.append(line);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stringBuffer.toString();
    }

    /**
     * 发送get请求
     * @param url
     * @param header 请求头
     * @return
     */
    public static String doGet(String url, Map<String, String> header) {
        String result = "";
        BufferedReader in = null;
        try {
            // 设置 url
            URL realUrl = new URL(url);
            URLConnection connection = realUrl.openConnection();
            // 设置 header
            for (String key : header.keySet()) {
                connection.setRequestProperty(key, header.get(key));
            }
            // 设置请求 body
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            return null;
        }
        return result;
    }
}
